<?php

namespace app\admin\controller;

use app\admin\model\User;
use app\admin\validate\User as ValidateUser;
use app\service\Tool;
use think\exception\ValidateException;
use think\facade\Session;

class Account extends Base
{
    public function index() {
        $this->logs('[管理员]消息视图');
        $userData = User::field('id,username,email,nickname,head_icon,signature')->find(Session::get('admin.user_id'));
        return view('index' , ['userData' => $userData]);
    }
    public function changePwd()
    {
        $this->logs('[管理员]更改密码视图');
        return view();
    }
    public function updatePwd()
    {
        $this->logs('[管理员]更改密码');
        $param = input();
        if(request()->isPost())
        {
            $uid = $this->admin['user_id'];
            $userData = User::where('id' , $uid)->find();
            if(md5(@$param['oldpwd']) != $userData->password) return $this->view('旧密码错误');
            if(@$param['newpwd'] != @$param['confirmpwd']) return $this->view('两次密码输入不一致');
            try{
                validate(ValidateUser::class)->scene('pwd')->check(['password' => $param['newpwd']]);
                $res = User::where('id' , $uid)->update(['password' => md5($param['newpwd'])]);
                if($res) return view('tip/index',['msg' => '更改成功']);
                return  view('tip/index',['msg' => '更改失败']);
            }catch(ValidateException $e)
            {
                return $this->view($e->getError());
            }
            
           
        }
    }
    public function doUpdate()
    {
        $this->logs('[管理员]更新消息');
        $param = input();
        if(request()->isPost())
        {
            $hasNick = User::where('nickname',$param['nickname'])->findOrEmpty()->isEmpty();
            $userData = User::find($this->admin['user_id']);
            if($userData->nickname != $param['nickname'] && !$hasNick) return view('tip/index',['msg' => '已存在该昵称，请更换另一个吧！']);
            $param = ['head_icon' => $param['head_icon'] , 'email' => @$param['email'] , 'signature' => @$param['signature'] , 'nickname' => @$param['nickname']];
            $uid = $this->admin['user_id'];
            $res = User::where('id' , $uid)->update($param);
            if($res) return view('tip/index',['msg' => '更改成功']);
            return  view('tip/index',['msg' => '更改失败']);
        }
    }
    public function uploadHeadIcon()
    {
        $file = request()->file('headIcon');
        $res = Tool::uploadImg($file, 'headIcon');
        return $res;
    }
}
